package com.aote.controller;

//体检预约

import com.alibaba.dubbo.config.annotation.Reference;
import com.aote.constant.MessageConstant;
import com.aote.constant.RedisMessageConstant;
import com.aote.entity.Result;
import com.aote.pojo.Order;
import com.aote.service.OrderService;
import com.aote.utils.TencentSMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;
//    在线体检预约
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        String telephone = (String) map.get("telephone");
//        从Redis中获取保存的验证码
        String code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");

//        将用户输入的验证码和redis中保存验证码进行比对

        if (code!=null && validateCode != null && code.equals(validateCode)){
            //        比对成功，调用服务完成预约业务处理
            map.put("orderType",Order.ORDERTYPE_WEIXIN);//设置预约类型，分为微信预约和电话预约

            try {
                Result  result = orderService.order(map); //通过dubbo远程调用服务实现在线预约
//                预约成功发送短信
                if (result.isFlag()){
                    try{
                        TencentSMSUtils.sendShortMessage(TencentSMSUtils.ORDER_NOTICE,telephone, (String) map.get("orderDate"));
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
                return result;
            } catch (Exception e){
                e.printStackTrace();
                return new Result(false,MessageConstant.ORDERSETTING_FAIL);
            }

        }else {
            //        比对不成功，返回结果给页面
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

//    根据预约id查询相关预约信息
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
